package org.jeecgframework.web.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.web.service.ZyEmailService;
import org.jeecgframework.web.system.pojo.base.ZyEmailEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/zyEmailController")
public class ZyEmailController {
	// Logger for this class
	private static final Logger logger = Logger.getLogger(ZyEmailController.class); // NOPMD by dzqThinkpad on 16-4-1 下午3:01
	@Autowired
	private ZyEmailService zyEmailService;

	@RequestMapping(params="send")
	@ResponseBody
	public AjaxJson sendEmail(ZyEmailEntity emailEntity, HttpServletRequest request,
			HttpServletResponse response) {
		// generate response message
		AjaxJson message = new AjaxJson();
		try {
			// validate input email
			this.validateEmail(emailEntity);
			// send email
			this.zyEmailService.sendEmail(emailEntity);

	        message.setMsg("邮件发送成功!");
        } catch (Exception e) {
        	message.setMsg(e.getMessage());
        	ZyEmailController.logger.error("邮件发送失败！");
	        e.printStackTrace();
        }
		
		return message;
	}
	
	private void validateEmail(ZyEmailEntity emailEntity) throws Exception {
		// receiver
		String emailReceiver = emailEntity.getEmailReceiver();
		// title 
		String emailSubject = emailEntity.getEmailSubject();
		
		// to do...
		// temp validate rules
		if(null == emailReceiver) {
			throw new Exception("邮件接收人不能为空！"); // NOPMD by dzqThinkpad on 16-4-1 下午3:01
		}
		if(null == emailSubject) {
			throw new Exception("邮件标题不能为空！"); // NOPMD by dzqThinkpad on 16-4-1 下午3:01
		}
	}
}
